home *** CD-ROM | disk | FTP | other *** search
/ SGI Freeware 1999 August / SGI Freeware 1999 August.iso / dist / fw_emacs.idb / usr / freeware / info / cl-2.z / cl-2
Encoding:
GNU Info File  |  1998-10-28  |  43.5 KB  |  1,041 lines

  1. This is Info file ../info/cl, produced by Makeinfo-1.64 from the input
  2. file cl.texi.
  3.  
  4.    This file documents the GNU Emacs Common Lisp emulation package.
  5.  
  6.    Copyright (C) 1993 Free Software Foundation, Inc.
  7.  
  8.    Permission is granted to make and distribute verbatim copies of this
  9. manual provided the copyright notice and this permission notice are
  10. preserved on all copies.
  11.  
  12.    Permission is granted to copy and distribute modified versions of
  13. this manual under the conditions for verbatim copying, provided also
  14. that the section entitled "GNU General Public License" is included
  15. exactly as in the original, and provided that the entire resulting
  16. derived work is distributed under the terms of a permission notice
  17. identical to this one.
  18.  
  19.    Permission is granted to copy and distribute translations of this
  20. manual into another language, under the above conditions for modified
  21. versions, except that the section entitled "GNU General Public License"
  22. may be included in a translation approved by the author instead of in
  23. the original English.
  24.  
  25. 
  26. File: cl,  Node: Modify Macros,  Next: Customizing Setf,  Prev: Basic Setf,  Up: Generalized Variables
  27.  
  28. Modify Macros
  29. -------------
  30.  
  31. This package defines a number of other macros besides `setf' that
  32. operate on generalized variables.  Many are interesting and useful even
  33. when the PLACE is just a variable name.
  34.  
  35.  - Special Form: psetf [PLACE FORM]...
  36.      This macro is to `setf' what `psetq' is to `setq': When several
  37.      PLACEs and FORMs are involved, the assignments take place in
  38.      parallel rather than sequentially.  Specifically, all subforms are
  39.      evaluated from left to right, then all the assignments are done
  40.      (in an undefined order).
  41.  
  42.  - Special Form: incf PLACE &optional X
  43.      This macro increments the number stored in PLACE by one, or by X
  44.      if specified.  The incremented value is returned.  For example,
  45.      `(incf i)' is equivalent to `(setq i (1+ i))', and `(incf (car x)
  46.      2)' is equivalent to `(setcar x (+ (car x) 2))'.
  47.  
  48.      Once again, care is taken to preserve the "apparent" order of
  49.      evaluation.  For example,
  50.  
  51.           (incf (aref vec (incf i)))
  52.  
  53.      appears to increment `i' once, then increment the element of `vec'
  54.      addressed by `i'; this is indeed exactly what it does, which means
  55.      the above form is *not* equivalent to the "obvious" expansion,
  56.  
  57.           (setf (aref vec (incf i)) (1+ (aref vec (incf i))))   ; Wrong!
  58.  
  59.      but rather to something more like
  60.  
  61.           (let ((temp (incf i)))
  62.             (setf (aref vec temp) (1+ (aref vec temp))))
  63.  
  64.      Again, all of this is taken care of automatically by `incf' and
  65.      the other generalized-variable macros.
  66.  
  67.      As a more Emacs-specific example of `incf', the expression `(incf
  68.      (point) N)' is essentially equivalent to `(forward-char N)'.
  69.  
  70.  - Special Form: decf PLACE &optional X
  71.      This macro decrements the number stored in PLACE by one, or by X
  72.      if specified.
  73.  
  74.  - Special Form: pop PLACE
  75.      This macro removes and returns the first element of the list stored
  76.      in PLACE.  It is analogous to `(prog1 (car PLACE) (setf PLACE (cdr
  77.      PLACE)))', except that it takes care to evaluate all subforms only
  78.      once.
  79.  
  80.  - Special Form: push X PLACE
  81.      This macro inserts X at the front of the list stored in PLACE.  It
  82.      is analogous to `(setf PLACE (cons X PLACE))', except for
  83.      evaluation of the subforms.
  84.  
  85.  - Special Form: pushnew X PLACE &key :test :test-not :key
  86.      This macro inserts X at the front of the list stored in PLACE, but
  87.      only if X was not `eql' to any existing element of the list.  The
  88.      optional keyword arguments are interpreted in the same way as for
  89.      `adjoin'.  *Note Lists as Sets::.
  90.  
  91.  - Special Form: shiftf PLACE... NEWVALUE
  92.      This macro shifts the PLACEs left by one, shifting in the value of
  93.      NEWVALUE (which may be any Lisp expression, not just a generalized
  94.      variable), and returning the value shifted out of the first PLACE.
  95.      Thus, `(shiftf A B C D)' is equivalent to
  96.  
  97.           (prog1
  98.               A
  99.             (psetf A B
  100.                    B C
  101.                    C D))
  102.  
  103.      except that the subforms of A, B, and C are actually evaluated
  104.      only once each and in the apparent order.
  105.  
  106.  - Special Form: rotatef PLACE...
  107.      This macro rotates the PLACEs left by one in circular fashion.
  108.      Thus, `(rotatef A B C D)' is equivalent to
  109.  
  110.           (psetf A B
  111.                  B C
  112.                  C D
  113.                  D A)
  114.  
  115.      except for the evaluation of subforms.  `rotatef' always returns
  116.      `nil'.  Note that `(rotatef A B)' conveniently exchanges A and B.
  117.  
  118.    The following macros were invented for this package; they have no
  119. analogues in Common Lisp.
  120.  
  121.  - Special Form: letf (BINDINGS...) FORMS...
  122.      This macro is analogous to `let', but for generalized variables
  123.      rather than just symbols.  Each BINDING should be of the form
  124.      `(PLACE VALUE)'; the original contents of the PLACEs are saved,
  125.      the VALUEs are stored in them, and then the body FORMs are
  126.      executed.  Afterwards, the PLACES are set back to their original
  127.      saved contents.  This cleanup happens even if the FORMs exit
  128.      irregularly due to a `throw' or an error.
  129.  
  130.      For example,
  131.  
  132.           (letf (((point) (point-min))
  133.                  (a 17))
  134.             ...)
  135.  
  136.      moves "point" in the current buffer to the beginning of the buffer,
  137.      and also binds `a' to 17 (as if by a normal `let', since `a' is
  138.      just a regular variable).  After the body exits, `a' is set back
  139.      to its original value and point is moved back to its original
  140.      position.
  141.  
  142.      Note that `letf' on `(point)' is not quite like a
  143.      `save-excursion', as the latter effectively saves a marker which
  144.      tracks insertions and deletions in the buffer.  Actually, a `letf'
  145.      of `(point-marker)' is much closer to this behavior.  (`point' and
  146.      `point-marker' are equivalent as `setf' places; each will accept
  147.      either an integer or a marker as the stored value.)
  148.  
  149.      Since generalized variables look like lists, `let''s shorthand of
  150.      using `foo' for `(foo nil)' as a BINDING would be ambiguous in
  151.      `letf' and is not allowed.
  152.  
  153.      However, a BINDING specifier may be a one-element list `(PLACE)',
  154.      which is similar to `(PLACE PLACE)'.  In other words, the PLACE is
  155.      not disturbed on entry to the body, and the only effect of the
  156.      `letf' is to restore the original value of PLACE afterwards.  (The
  157.      redundant access-and-store suggested by the `(PLACE PLACE)'
  158.      example does not actually occur.)
  159.  
  160.      In most cases, the PLACE must have a well-defined value on entry
  161.      to the `letf' form.  The only exceptions are plain variables and
  162.      calls to `symbol-value' and `symbol-function'.  If the symbol is
  163.      not bound on entry, it is simply made unbound by `makunbound' or
  164.      `fmakunbound' on exit.
  165.  
  166.  - Special Form: letf* (BINDINGS...) FORMS...
  167.      This macro is to `letf' what `let*' is to `let': It does the
  168.      bindings in sequential rather than parallel order.
  169.  
  170.  - Special Form: callf FUNCTION PLACE ARGS...
  171.      This is the "generic" modify macro.  It calls FUNCTION, which
  172.      should be an unquoted function name, macro name, or lambda.  It
  173.      passes PLACE and ARGS as arguments, and assigns the result back to
  174.      PLACE.  For example, `(incf PLACE N)' is the same as `(callf +
  175.      PLACE N)'.  Some more examples:
  176.  
  177.           (callf abs my-number)
  178.           (callf concat (buffer-name) "<" (int-to-string n) ">")
  179.           (callf union happy-people (list joe bob) :test 'same-person)
  180.  
  181.      *Note Customizing Setf::, for `define-modify-macro', a way to
  182.      create even more concise notations for modify macros.  Note again
  183.      that `callf' is an extension to standard Common Lisp.
  184.  
  185.  - Special Form: callf2 FUNCTION ARG1 PLACE ARGS...
  186.      This macro is like `callf', except that PLACE is the *second*
  187.      argument of FUNCTION rather than the first.  For example, `(push X
  188.      PLACE)' is equivalent to `(callf2 cons X PLACE)'.
  189.  
  190.    The `callf' and `callf2' macros serve as building blocks for other
  191. macros like `incf', `pushnew', and `define-modify-macro'.  The `letf'
  192. and `letf*' macros are used in the processing of symbol macros; *note
  193. Macro Bindings::..
  194.  
  195. 
  196. File: cl,  Node: Customizing Setf,  Prev: Modify Macros,  Up: Generalized Variables
  197.  
  198. Customizing Setf
  199. ----------------
  200.  
  201. Common Lisp defines three macros, `define-modify-macro', `defsetf', and
  202. `define-setf-method', that allow the user to extend generalized
  203. variables in various ways.
  204.  
  205.  - Special Form: define-modify-macro NAME ARGLIST FUNCTION [DOC-STRING]
  206.      This macro defines a "read-modify-write" macro similar to `incf'
  207.      and `decf'.  The macro NAME is defined to take a PLACE argument
  208.      followed by additional arguments described by ARGLIST.  The call
  209.  
  210.           (NAME PLACE ARGS...)
  211.  
  212.      will be expanded to
  213.  
  214.           (callf FUNC PLACE ARGS...)
  215.  
  216.      which in turn is roughly equivalent to
  217.  
  218.           (setf PLACE (FUNC PLACE ARGS...))
  219.  
  220.      For example:
  221.  
  222.           (define-modify-macro incf (&optional (n 1)) +)
  223.           (define-modify-macro concatf (&rest args) concat)
  224.  
  225.      Note that `&key' is not allowed in ARGLIST, but `&rest' is
  226.      sufficient to pass keywords on to the function.
  227.  
  228.      Most of the modify macros defined by Common Lisp do not exactly
  229.      follow the pattern of `define-modify-macro'.  For example, `push'
  230.      takes its arguments in the wrong order, and `pop' is completely
  231.      irregular.  You can define these macros "by hand" using
  232.      `get-setf-method', or consult the source file `cl-macs.el' to see
  233.      how to use the internal `setf' building blocks.
  234.  
  235.  - Special Form: defsetf ACCESS-FN UPDATE-FN
  236.      This is the simpler of two `defsetf' forms.  Where ACCESS-FN is
  237.      the name of a function which accesses a place, this declares
  238.      UPDATE-FN to be the corresponding store function.  From now on,
  239.  
  240.           (setf (ACCESS-FN ARG1 ARG2 ARG3) VALUE)
  241.  
  242.      will be expanded to
  243.  
  244.           (UPDATE-FN ARG1 ARG2 ARG3 VALUE)
  245.  
  246.      The UPDATE-FN is required to be either a true function, or a macro
  247.      which evaluates its arguments in a function-like way.  Also, the
  248.      UPDATE-FN is expected to return VALUE as its result.  Otherwise,
  249.      the above expansion would not obey the rules for the way `setf' is
  250.      supposed to behave.
  251.  
  252.      As a special (non-Common-Lisp) extension, a third argument of `t'
  253.      to `defsetf' says that the `update-fn''s return value is not
  254.      suitable, so that the above `setf' should be expanded to something
  255.      more like
  256.  
  257.           (let ((temp VALUE))
  258.             (UPDATE-FN ARG1 ARG2 ARG3 temp)
  259.             temp)
  260.  
  261.      Some examples of the use of `defsetf', drawn from the standard
  262.      suite of setf methods, are:
  263.  
  264.           (defsetf car setcar)
  265.           (defsetf symbol-value set)
  266.           (defsetf buffer-name rename-buffer t)
  267.  
  268.  - Special Form: defsetf ACCESS-FN ARGLIST (STORE-VAR) FORMS...
  269.      This is the second, more complex, form of `defsetf'.  It is rather
  270.      like `defmacro' except for the additional STORE-VAR argument.  The
  271.      FORMS should return a Lisp form which stores the value of
  272.      STORE-VAR into the generalized variable formed by a call to
  273.      ACCESS-FN with arguments described by ARGLIST.  The FORMS may
  274.      begin with a string which documents the `setf' method (analogous
  275.      to the doc string that appears at the front of a function).
  276.  
  277.      For example, the simple form of `defsetf' is shorthand for
  278.  
  279.           (defsetf ACCESS-FN (&rest args) (store)
  280.             (append '(UPDATE-FN) args (list store)))
  281.  
  282.      The Lisp form that is returned can access the arguments from
  283.      ARGLIST and STORE-VAR in an unrestricted fashion; macros like
  284.      `setf' and `incf' which invoke this setf-method will insert
  285.      temporary variables as needed to make sure the apparent order of
  286.      evaluation is preserved.
  287.  
  288.      Another example drawn from the standard package:
  289.  
  290.           (defsetf nth (n x) (store)
  291.             (list 'setcar (list 'nthcdr n x) store))
  292.  
  293.  - Special Form: define-setf-method ACCESS-FN ARGLIST FORMS...
  294.      This is the most general way to create new place forms.  When a
  295.      `setf' to ACCESS-FN with arguments described by ARGLIST is
  296.      expanded, the FORMS are evaluated and must return a list of five
  297.      items:
  298.  
  299.        1. A list of "temporary variables".
  300.  
  301.        2. A list of "value forms" corresponding to the temporary
  302.           variables above.  The temporary variables will be bound to
  303.           these value forms as the first step of any operation on the
  304.           generalized variable.
  305.  
  306.        3. A list of exactly one "store variable" (generally obtained
  307.           from a call to `gensym').
  308.  
  309.        4. A Lisp form which stores the contents of the store variable
  310.           into the generalized variable, assuming the temporaries have
  311.           been bound as described above.
  312.  
  313.        5. A Lisp form which accesses the contents of the generalized
  314.           variable, assuming the temporaries have been bound.
  315.  
  316.      This is exactly like the Common Lisp macro of the same name,
  317.      except that the method returns a list of five values rather than
  318.      the five values themselves, since Emacs Lisp does not support
  319.      Common Lisp's notion of multiple return values.
  320.  
  321.      Once again, the FORMS may begin with a documentation string.
  322.  
  323.      A setf-method should be maximally conservative with regard to
  324.      temporary variables.  In the setf-methods generated by `defsetf',
  325.      the second return value is simply the list of arguments in the
  326.      place form, and the first return value is a list of a
  327.      corresponding number of temporary variables generated by `gensym'.
  328.      Macros like `setf' and `incf' which use this setf-method will
  329.      optimize away most temporaries that turn out to be unnecessary, so
  330.      there is little reason for the setf-method itself to optimize.
  331.  
  332.  - Function: get-setf-method PLACE &optional ENV
  333.      This function returns the setf-method for PLACE, by invoking the
  334.      definition previously recorded by `defsetf' or
  335.      `define-setf-method'.  The result is a list of five values as
  336.      described above.  You can use this function to build your own
  337.      `incf'-like modify macros.  (Actually, it is better to use the
  338.      internal functions `cl-setf-do-modify' and `cl-setf-do-store',
  339.      which are a bit easier to use and which also do a number of
  340.      optimizations; consult the source code for the `incf' function for
  341.      a simple example.)
  342.  
  343.      The argument ENV specifies the "environment" to be passed on to
  344.      `macroexpand' if `get-setf-method' should need to expand a macro
  345.      in PLACE.  It should come from an `&environment' argument to the
  346.      macro or setf-method that called `get-setf-method'.
  347.  
  348.      See also the source code for the setf-methods for `apply' and
  349.      `substring', each of which works by calling `get-setf-method' on a
  350.      simpler case, then massaging the result in various ways.
  351.  
  352.    Modern Common Lisp defines a second, independent way to specify the
  353. `setf' behavior of a function, namely "`setf' functions" whose names
  354. are lists `(setf NAME)' rather than symbols.  For example, `(defun
  355. (setf foo) ...)' defines the function that is used when `setf' is
  356. applied to `foo'.  This package does not currently support `setf'
  357. functions.  In particular, it is a compile-time error to use `setf' on
  358. a form which has not already been `defsetf''d or otherwise declared; in
  359. newer Common Lisps, this would not be an error since the function
  360. `(setf FUNC)' might be defined later.
  361.  
  362. 
  363. File: cl,  Node: Variable Bindings,  Next: Conditionals,  Prev: Generalized Variables,  Up: Control Structure
  364.  
  365. Variable Bindings
  366. =================
  367.  
  368. These Lisp forms make bindings to variables and function names,
  369. analogous to Lisp's built-in `let' form.
  370.  
  371.    *Note Modify Macros::, for the `letf' and `letf*' forms which are
  372. also related to variable bindings.
  373.  
  374. * Menu:
  375.  
  376. * Dynamic Bindings::     The `progv' form
  377. * Lexical Bindings::     `lexical-let' and lexical closures
  378. * Function Bindings::    `flet' and `labels'
  379. * Macro Bindings::       `macrolet' and `symbol-macrolet'
  380.  
  381. 
  382. File: cl,  Node: Dynamic Bindings,  Next: Lexical Bindings,  Prev: Variable Bindings,  Up: Variable Bindings
  383.  
  384. Dynamic Bindings
  385. ----------------
  386.  
  387. The standard `let' form binds variables whose names are known at
  388. compile-time.  The `progv' form provides an easy way to bind variables
  389. whose names are computed at run-time.
  390.  
  391.  - Special Form: progv SYMBOLS VALUES FORMS...
  392.      This form establishes `let'-style variable bindings on a set of
  393.      variables computed at run-time.  The expressions SYMBOLS and
  394.      VALUES are evaluated, and must return lists of symbols and values,
  395.      respectively.  The symbols are bound to the corresponding values
  396.      for the duration of the body FORMs.  If VALUES is shorter than
  397.      SYMBOLS, the last few symbols are made unbound (as if by
  398.      `makunbound') inside the body.  If SYMBOLS is shorter than VALUES,
  399.      the excess values are ignored.
  400.  
  401. 
  402. File: cl,  Node: Lexical Bindings,  Next: Function Bindings,  Prev: Dynamic Bindings,  Up: Variable Bindings
  403.  
  404. Lexical Bindings
  405. ----------------
  406.  
  407. The "CL" package defines the following macro which more closely follows
  408. the Common Lisp `let' form:
  409.  
  410.  - Special Form: lexical-let (BINDINGS...) FORMS...
  411.      This form is exactly like `let' except that the bindings it
  412.      establishes are purely lexical.  Lexical bindings are similar to
  413.      local variables in a language like C:  Only the code physically
  414.      within the body of the `lexical-let' (after macro expansion) may
  415.      refer to the bound variables.
  416.  
  417.           (setq a 5)
  418.           (defun foo (b) (+ a b))
  419.           (let ((a 2)) (foo a))
  420.                => 4
  421.           (lexical-let ((a 2)) (foo a))
  422.                => 7
  423.  
  424.      In this example, a regular `let' binding of `a' actually makes a
  425.      temporary change to the global variable `a', so `foo' is able to
  426.      see the binding of `a' to 2.  But `lexical-let' actually creates a
  427.      distinct local variable `a' for use within its body, without any
  428.      effect on the global variable of the same name.
  429.  
  430.      The most important use of lexical bindings is to create "closures".
  431.      A closure is a function object that refers to an outside lexical
  432.      variable.  For example:
  433.  
  434.           (defun make-adder (n)
  435.             (lexical-let ((n n))
  436.               (function (lambda (m) (+ n m)))))
  437.           (setq add17 (make-adder 17))
  438.           (funcall add17 4)
  439.                => 21
  440.  
  441.      The call `(make-adder 17)' returns a function object which adds 17
  442.      to its argument.  If `let' had been used instead of `lexical-let',
  443.      the function object would have referred to the global `n', which
  444.      would have been bound to 17 only during the call to `make-adder'
  445.      itself.
  446.  
  447.           (defun make-counter ()
  448.             (lexical-let ((n 0))
  449.               (function* (lambda (&optional (m 1)) (incf n m)))))
  450.           (setq count-1 (make-counter))
  451.           (funcall count-1 3)
  452.                => 3
  453.           (funcall count-1 14)
  454.                => 17
  455.           (setq count-2 (make-counter))
  456.           (funcall count-2 5)
  457.                => 5
  458.           (funcall count-1 2)
  459.                => 19
  460.           (funcall count-2)
  461.                => 6
  462.  
  463.      Here we see that each call to `make-counter' creates a distinct
  464.      local variable `n', which serves as a private counter for the
  465.      function object that is returned.
  466.  
  467.      Closed-over lexical variables persist until the last reference to
  468.      them goes away, just like all other Lisp objects.  For example,
  469.      `count-2' refers to a function object which refers to an instance
  470.      of the variable `n'; this is the only reference to that variable,
  471.      so after `(setq count-2 nil)' the garbage collector would be able
  472.      to delete this instance of `n'.  Of course, if a `lexical-let'
  473.      does not actually create any closures, then the lexical variables
  474.      are free as soon as the `lexical-let' returns.
  475.  
  476.      Many closures are used only during the extent of the bindings they
  477.      refer to; these are known as "downward funargs" in Lisp parlance.
  478.      When a closure is used in this way, regular Emacs Lisp dynamic
  479.      bindings suffice and will be more efficient than `lexical-let'
  480.      closures:
  481.  
  482.           (defun add-to-list (x list)
  483.             (mapcar (function (lambda (y) (+ x y))) list))
  484.           (add-to-list 7 '(1 2 5))
  485.                => (8 9 12)
  486.  
  487.      Since this lambda is only used while `x' is still bound, it is not
  488.      necessary to make a true closure out of it.
  489.  
  490.      You can use `defun' or `flet' inside a `lexical-let' to create a
  491.      named closure.  If several closures are created in the body of a
  492.      single `lexical-let', they all close over the same instance of the
  493.      lexical variable.
  494.  
  495.      The `lexical-let' form is an extension to Common Lisp.  In true
  496.      Common Lisp, all bindings are lexical unless declared otherwise.
  497.  
  498.  - Special Form: lexical-let* (BINDINGS...) FORMS...
  499.      This form is just like `lexical-let', except that the bindings are
  500.      made sequentially in the manner of `let*'.
  501.  
  502. 
  503. File: cl,  Node: Function Bindings,  Next: Macro Bindings,  Prev: Lexical Bindings,  Up: Variable Bindings
  504.  
  505. Function Bindings
  506. -----------------
  507.  
  508. These forms make `let'-like bindings to functions instead of variables.
  509.  
  510.  - Special Form: flet (BINDINGS...) FORMS...
  511.      This form establishes `let'-style bindings on the function cells
  512.      of symbols rather than on the value cells.  Each BINDING must be a
  513.      list of the form `(NAME ARGLIST FORMS...)', which defines a
  514.      function exactly as if it were a `defun*' form.  The function NAME
  515.      is defined accordingly for the duration of the body of the `flet';
  516.      then the old function definition, or lack thereof, is restored.
  517.  
  518.      While `flet' in Common Lisp establishes a lexical binding of NAME,
  519.      Emacs Lisp `flet' makes a dynamic binding.  The result is that
  520.      `flet' affects indirect calls to a function as well as calls
  521.      directly inside the `flet' form itself.
  522.  
  523.      You can use `flet' to disable or modify the behavior of a function
  524.      in a temporary fashion.  This will even work on Emacs primitives,
  525.      although note that some calls to primitive functions internal to
  526.      Emacs are made without going through the symbol's function cell,
  527.      and so will not be affected by `flet'.  For example,
  528.  
  529.           (flet ((message (&rest args) (push args saved-msgs)))
  530.             (do-something))
  531.  
  532.      This code attempts to replace the built-in function `message' with
  533.      a function that simply saves the messages in a list rather than
  534.      displaying them.  The original definition of `message' will be
  535.      restored after `do-something' exits.  This code will work fine on
  536.      messages generated by other Lisp code, but messages generated
  537.      directly inside Emacs will not be caught since they make direct
  538.      C-language calls to the message routines rather than going through
  539.      the Lisp `message' function.
  540.  
  541.      Functions defined by `flet' may use the full Common Lisp argument
  542.      notation supported by `defun*'; also, the function body is
  543.      enclosed in an implicit block as if by `defun*'.  *Note Program
  544.      Structure::.
  545.  
  546.  - Special Form: labels (BINDINGS...) FORMS...
  547.      The `labels' form is like `flet', except that it makes lexical
  548.      bindings of the function names rather than dynamic bindings.  (In
  549.      true Common Lisp, both `flet' and `labels' make lexical bindings
  550.      of slightly different sorts; since Emacs Lisp is dynamically bound
  551.      by default, it seemed more appropriate for `flet' also to use
  552.      dynamic binding.  The `labels' form, with its lexical binding, is
  553.      fully compatible with Common Lisp.)
  554.  
  555.      Lexical scoping means that all references to the named functions
  556.      must appear physically within the body of the `labels' form.
  557.      References may appear both in the body FORMS of `labels' itself,
  558.      and in the bodies of the functions themselves.  Thus, `labels' can
  559.      define local recursive functions, or mutually-recursive sets of
  560.      functions.
  561.  
  562.      A "reference" to a function name is either a call to that
  563.      function, or a use of its name quoted by `quote' or `function' to
  564.      be passed on to, say, `mapcar'.
  565.  
  566. 
  567. File: cl,  Node: Macro Bindings,  Prev: Function Bindings,  Up: Variable Bindings
  568.  
  569. Macro Bindings
  570. --------------
  571.  
  572. These forms create local macros and "symbol macros."
  573.  
  574.  - Special Form: macrolet (BINDINGS...) FORMS...
  575.      This form is analogous to `flet', but for macros instead of
  576.      functions.  Each BINDING is a list of the same form as the
  577.      arguments to `defmacro*' (i.e., a macro name, argument list, and
  578.      macro-expander forms).  The macro is defined accordingly for use
  579.      within the body of the `macrolet'.
  580.  
  581.      Because of the nature of macros, `macrolet' is lexically scoped
  582.      even in Emacs Lisp:  The `macrolet' binding will affect only calls
  583.      that appear physically within the body FORMS, possibly after
  584.      expansion of other macros in the body.
  585.  
  586.  - Special Form: symbol-macrolet (BINDINGS...) FORMS...
  587.      This form creates "symbol macros", which are macros that look like
  588.      variable references rather than function calls.  Each BINDING is a
  589.      list `(VAR EXPANSION)'; any reference to VAR within the body FORMS
  590.      is replaced by EXPANSION.
  591.  
  592.           (setq bar '(5 . 9))
  593.           (symbol-macrolet ((foo (car bar)))
  594.             (incf foo))
  595.           bar
  596.                => (6 . 9)
  597.  
  598.      A `setq' of a symbol macro is treated the same as a `setf'.  I.e.,
  599.      `(setq foo 4)' in the above would be equivalent to `(setf foo 4)',
  600.      which in turn expands to `(setf (car bar) 4)'.
  601.  
  602.      Likewise, a `let' or `let*' binding a symbol macro is treated like
  603.      a `letf' or `letf*'.  This differs from true Common Lisp, where
  604.      the rules of lexical scoping cause a `let' binding to shadow a
  605.      `symbol-macrolet' binding.  In this package, only `lexical-let'
  606.      and `lexical-let*' will shadow a symbol macro.
  607.  
  608.      There is no analogue of `defmacro' for symbol macros; all symbol
  609.      macros are local.  A typical use of `symbol-macrolet' is in the
  610.      expansion of another macro:
  611.  
  612.           (defmacro* my-dolist ((x list) &rest body)
  613.             (let ((var (gensym)))
  614.               (list 'loop 'for var 'on list 'do
  615.                     (list* 'symbol-macrolet (list (list x (list 'car var)))
  616.                            body))))
  617.           
  618.           (setq mylist '(1 2 3 4))
  619.           (my-dolist (x mylist) (incf x))
  620.           mylist
  621.                => (2 3 4 5)
  622.  
  623.      In this example, the `my-dolist' macro is similar to `dolist'
  624.      (*note Iteration::.) except that the variable `x' becomes a true
  625.      reference onto the elements of the list.  The `my-dolist' call
  626.      shown here expands to
  627.  
  628.           (loop for G1234 on mylist do
  629.                 (symbol-macrolet ((x (car G1234)))
  630.                   (incf x)))
  631.  
  632.      which in turn expands to
  633.  
  634.           (loop for G1234 on mylist do (incf (car G1234)))
  635.  
  636.      *Note Loop Facility::, for a description of the `loop' macro.
  637.      This package defines a nonstandard `in-ref' loop clause that works
  638.      much like `my-dolist'.
  639.  
  640. 
  641. File: cl,  Node: Conditionals,  Next: Blocks and Exits,  Prev: Variable Bindings,  Up: Control Structure
  642.  
  643. Conditionals
  644. ============
  645.  
  646. These conditional forms augment Emacs Lisp's simple `if', `and', `or',
  647. and `cond' forms.
  648.  
  649.  - Special Form: when TEST FORMS...
  650.      This is a variant of `if' where there are no "else" forms, and
  651.      possibly several "then" forms.  In particular,
  652.  
  653.           (when TEST A B C)
  654.  
  655.      is entirely equivalent to
  656.  
  657.           (if TEST (progn A B C) nil)
  658.  
  659.  - Special Form: unless TEST FORMS...
  660.      This is a variant of `if' where there are no "then" forms, and
  661.      possibly several "else" forms:
  662.  
  663.           (unless TEST A B C)
  664.  
  665.      is entirely equivalent to
  666.  
  667.           (when (not TEST) A B C)
  668.  
  669.  - Special Form: case KEYFORM CLAUSE...
  670.      This macro evaluates KEYFORM, then compares it with the key values
  671.      listed in the various CLAUSEs.  Whichever clause matches the key
  672.      is executed; comparison is done by `eql'.  If no clause matches,
  673.      the `case' form returns `nil'.  The clauses are of the form
  674.  
  675.           (KEYLIST BODY-FORMS...)
  676.  
  677.      where KEYLIST is a list of key values.  If there is exactly one
  678.      value, and it is not a cons cell or the symbol `nil' or `t', then
  679.      it can be used by itself as a KEYLIST without being enclosed in a
  680.      list.  All key values in the `case' form must be distinct.  The
  681.      final clauses may use `t' in place of a KEYLIST to indicate a
  682.      default clause that should be taken if none of the other clauses
  683.      match.  (The symbol `otherwise' is also recognized in place of
  684.      `t'.  To make a clause that matches the actual symbol `t', `nil',
  685.      or `otherwise', enclose the symbol in a list.)
  686.  
  687.      For example, this expression reads a keystroke, then does one of
  688.      four things depending on whether it is an `a', a `b', a RET or
  689.      LFD, or anything else.
  690.  
  691.           (case (read-char)
  692.             (?a (do-a-thing))
  693.             (?b (do-b-thing))
  694.             ((?\r ?\n) (do-ret-thing))
  695.             (t (do-other-thing)))
  696.  
  697.  - Special Form: ecase KEYFORM CLAUSE...
  698.      This macro is just like `case', except that if the key does not
  699.      match any of the clauses, an error is signaled rather than simply
  700.      returning `nil'.
  701.  
  702.  - Special Form: typecase KEYFORM CLAUSE...
  703.      This macro is a version of `case' that checks for types rather
  704.      than values.  Each CLAUSE is of the form `(TYPE BODY...)'.  *Note
  705.      Type Predicates::, for a description of type specifiers.  For
  706.      example,
  707.  
  708.           (typecase x
  709.             (integer (munch-integer x))
  710.             (float (munch-float x))
  711.             (string (munch-integer (string-to-int x)))
  712.             (t (munch-anything x)))
  713.  
  714.      The type specifier `t' matches any type of object; the word
  715.      `otherwise' is also allowed.  To make one clause match any of
  716.      several types, use an `(or ...)' type specifier.
  717.  
  718.  - Special Form: etypecase KEYFORM CLAUSE...
  719.      This macro is just like `typecase', except that if the key does
  720.      not match any of the clauses, an error is signaled rather than
  721.      simply returning `nil'.
  722.  
  723. 
  724. File: cl,  Node: Blocks and Exits,  Next: Iteration,  Prev: Conditionals,  Up: Control Structure
  725.  
  726. Blocks and Exits
  727. ================
  728.  
  729. Common Lisp "blocks" provide a non-local exit mechanism very similar to
  730. `catch' and `throw', but lexically rather than dynamically scoped.
  731. This package actually implements `block' in terms of `catch'; however,
  732. the lexical scoping allows the optimizing byte-compiler to omit the
  733. costly `catch' step if the body of the block does not actually
  734. `return-from' the block.
  735.  
  736.  - Special Form: block NAME FORMS...
  737.      The FORMS are evaluated as if by a `progn'.  However, if any of
  738.      the FORMS execute `(return-from NAME)', they will jump out and
  739.      return directly from the `block' form.  The `block' returns the
  740.      result of the last FORM unless a `return-from' occurs.
  741.  
  742.      The `block'/`return-from' mechanism is quite similar to the
  743.      `catch'/`throw' mechanism.  The main differences are that block
  744.      NAMEs are unevaluated symbols, rather than forms (such as quoted
  745.      symbols) which evaluate to a tag at run-time; and also that blocks
  746.      are lexically scoped whereas `catch'/`throw' are dynamically
  747.      scoped.  This means that functions called from the body of a
  748.      `catch' can also `throw' to the `catch', but the `return-from'
  749.      referring to a block name must appear physically within the FORMS
  750.      that make up the body of the block.  They may not appear within
  751.      other called functions, although they may appear within macro
  752.      expansions or `lambda's in the body.  Block names and `catch'
  753.      names form independent name-spaces.
  754.  
  755.      In true Common Lisp, `defun' and `defmacro' surround the function
  756.      or expander bodies with implicit blocks with the same name as the
  757.      function or macro.  This does not occur in Emacs Lisp, but this
  758.      package provides `defun*' and `defmacro*' forms which do create
  759.      the implicit block.
  760.  
  761.      The Common Lisp looping constructs defined by this package, such
  762.      as `loop' and `dolist', also create implicit blocks just as in
  763.      Common Lisp.
  764.  
  765.      Because they are implemented in terms of Emacs Lisp `catch' and
  766.      `throw', blocks have the same overhead as actual `catch'
  767.      constructs (roughly two function calls).  However, Zawinski and
  768.      Furuseth's optimizing byte compiler (standard in Emacs 19) will
  769.      optimize away the `catch' if the block does not in fact contain
  770.      any `return' or `return-from' calls that jump to it.  This means
  771.      that `do' loops and `defun*' functions which don't use `return'
  772.      don't pay the overhead to support it.
  773.  
  774.  - Special Form: return-from NAME [RESULT]
  775.      This macro returns from the block named NAME, which must be an
  776.      (unevaluated) symbol.  If a RESULT form is specified, it is
  777.      evaluated to produce the result returned from the `block'.
  778.      Otherwise, `nil' is returned.
  779.  
  780.  - Special Form: return [RESULT]
  781.      This macro is exactly like `(return-from nil RESULT)'.  Common
  782.      Lisp loops like `do' and `dolist' implicitly enclose themselves in
  783.      `nil' blocks.
  784.  
  785. 
  786. File: cl,  Node: Iteration,  Next: Loop Facility,  Prev: Blocks and Exits,  Up: Control Structure
  787.  
  788. Iteration
  789. =========
  790.  
  791. The macros described here provide more sophisticated, high-level
  792. looping constructs to complement Emacs Lisp's basic `while' loop.
  793.  
  794.  - Special Form: loop FORMS...
  795.      The "CL" package supports both the simple, old-style meaning of
  796.      `loop' and the extremely powerful and flexible feature known as
  797.      the "Loop Facility" or "Loop Macro".  This more advanced facility
  798.      is discussed in the following section; *note Loop Facility::..
  799.      The simple form of `loop' is described here.
  800.  
  801.      If `loop' is followed by zero or more Lisp expressions, then
  802.      `(loop EXPRS...)' simply creates an infinite loop executing the
  803.      expressions over and over.  The loop is enclosed in an implicit
  804.      `nil' block.  Thus,
  805.  
  806.           (loop (foo)  (if (no-more) (return 72))  (bar))
  807.  
  808.      is exactly equivalent to
  809.  
  810.           (block nil (while t (foo)  (if (no-more) (return 72))  (bar)))
  811.  
  812.      If any of the expressions are plain symbols, the loop is instead
  813.      interpreted as a Loop Macro specification as described later.
  814.      (This is not a restriction in practice, since a plain symbol in
  815.      the above notation would simply access and throw away the value of
  816.      a variable.)
  817.  
  818.  - Special Form: do (SPEC...) (END-TEST [RESULT...]) FORMS...
  819.      This macro creates a general iterative loop.  Each SPEC is of the
  820.      form
  821.  
  822.           (VAR [INIT [STEP]])
  823.  
  824.      The loop works as follows:  First, each VAR is bound to the
  825.      associated INIT value as if by a `let' form.  Then, in each
  826.      iteration of the loop, the END-TEST is evaluated; if true, the
  827.      loop is finished.  Otherwise, the body FORMS are evaluated, then
  828.      each VAR is set to the associated STEP expression (as if by a
  829.      `psetq' form) and the next iteration begins.  Once the END-TEST
  830.      becomes true, the RESULT forms are evaluated (with the VARs still
  831.      bound to their values) to produce the result returned by `do'.
  832.  
  833.      The entire `do' loop is enclosed in an implicit `nil' block, so
  834.      that you can use `(return)' to break out of the loop at any time.
  835.  
  836.      If there are no RESULT forms, the loop returns `nil'.  If a given
  837.      VAR has no STEP form, it is bound to its INIT value but not
  838.      otherwise modified during the `do' loop (unless the code
  839.      explicitly modifies it); this case is just a shorthand for putting
  840.      a `(let ((VAR INIT)) ...)' around the loop.  If INIT is also
  841.      omitted it defaults to `nil', and in this case a plain `VAR' can
  842.      be used in place of `(VAR)', again following the analogy with
  843.      `let'.
  844.  
  845.      This example (from Steele) illustrates a loop which applies the
  846.      function `f' to successive pairs of values from the lists `foo'
  847.      and `bar'; it is equivalent to the call `(mapcar* 'f foo bar)'.
  848.      Note that this loop has no body FORMS at all, performing all its
  849.      work as side effects of the rest of the loop.
  850.  
  851.           (do ((x foo (cdr x))
  852.                (y bar (cdr y))
  853.                (z nil (cons (f (car x) (car y)) z)))
  854.             ((or (null x) (null y))
  855.              (nreverse z)))
  856.  
  857.  - Special Form: do* (SPEC...) (END-TEST [RESULT...]) FORMS...
  858.      This is to `do' what `let*' is to `let'.  In particular, the
  859.      initial values are bound as if by `let*' rather than `let', and
  860.      the steps are assigned as if by `setq' rather than `psetq'.
  861.  
  862.      Here is another way to write the above loop:
  863.  
  864.           (do* ((xp foo (cdr xp))
  865.                 (yp bar (cdr yp))
  866.                 (x (car xp) (car xp))
  867.                 (y (car yp) (car yp))
  868.                 z)
  869.             ((or (null xp) (null yp))
  870.              (nreverse z))
  871.             (push (f x y) z))
  872.  
  873.  - Special Form: dolist (VAR LIST [RESULT]) FORMS...
  874.      This is a more specialized loop which iterates across the elements
  875.      of a list.  LIST should evaluate to a list; the body FORMS are
  876.      executed with VAR bound to each element of the list in turn.
  877.      Finally, the RESULT form (or `nil') is evaluated with VAR bound to
  878.      `nil' to produce the result returned by the loop.  The loop is
  879.      surrounded by an implicit `nil' block.
  880.  
  881.  - Special Form: dotimes (VAR COUNT [RESULT]) FORMS...
  882.      This is a more specialized loop which iterates a specified number
  883.      of times.  The body is executed with VAR bound to the integers
  884.      from zero (inclusive) to COUNT (exclusive), in turn.  Then the
  885.      `result' form is evaluated with VAR bound to the total number of
  886.      iterations that were done (i.e., `(max 0 COUNT)') to get the
  887.      return value for the loop form.  The loop is surrounded by an
  888.      implicit `nil' block.
  889.  
  890.  - Special Form: do-symbols (VAR [OBARRAY [RESULT]]) FORMS...
  891.      This loop iterates over all interned symbols.  If OBARRAY is
  892.      specified and is not `nil', it loops over all symbols in that
  893.      obarray.  For each symbol, the body FORMS are evaluated with VAR
  894.      bound to that symbol.  The symbols are visited in an unspecified
  895.      order.  Afterward the RESULT form, if any, is evaluated (with VAR
  896.      bound to `nil') to get the return value.  The loop is surrounded
  897.      by an implicit `nil' block.
  898.  
  899.  - Special Form: do-all-symbols (VAR [RESULT]) FORMS...
  900.      This is identical to `do-symbols' except that the OBARRAY argument
  901.      is omitted; it always iterates over the default obarray.
  902.  
  903.    *Note Mapping over Sequences::, for some more functions for
  904. iterating over vectors or lists.
  905.  
  906. 
  907. File: cl,  Node: Loop Facility,  Next: Multiple Values,  Prev: Iteration,  Up: Control Structure
  908.  
  909. Loop Facility
  910. =============
  911.  
  912. A common complaint with Lisp's traditional looping constructs is that
  913. they are either too simple and limited, such as Common Lisp's `dotimes'
  914. or Emacs Lisp's `while', or too unreadable and obscure, like Common
  915. Lisp's `do' loop.
  916.  
  917.    To remedy this, recent versions of Common Lisp have added a new
  918. construct called the "Loop Facility" or "`loop' macro," with an
  919. easy-to-use but very powerful and expressive syntax.
  920.  
  921. * Menu:
  922.  
  923. * Loop Basics::           `loop' macro, basic clause structure
  924. * Loop Examples::         Working examples of `loop' macro
  925. * For Clauses::           Clauses introduced by `for' or `as'
  926. * Iteration Clauses::     `repeat', `while', `thereis', etc.
  927. * Accumulation Clauses::  `collect', `sum', `maximize', etc.
  928. * Other Clauses::         `with', `if', `initially', `finally'
  929.  
  930. 
  931. File: cl,  Node: Loop Basics,  Next: Loop Examples,  Prev: Loop Facility,  Up: Loop Facility
  932.  
  933. Loop Basics
  934. -----------
  935.  
  936. The `loop' macro essentially creates a mini-language within Lisp that
  937. is specially tailored for describing loops.  While this language is a
  938. little strange-looking by the standards of regular Lisp, it turns out
  939. to be very easy to learn and well-suited to its purpose.
  940.  
  941.    Since `loop' is a macro, all parsing of the loop language takes
  942. place at byte-compile time; compiled `loop's are just as efficient as
  943. the equivalent `while' loops written longhand.
  944.  
  945.  - Special Form: loop CLAUSES...
  946.      A loop construct consists of a series of CLAUSEs, each introduced
  947.      by a symbol like `for' or `do'.  Clauses are simply strung
  948.      together in the argument list of `loop', with minimal extra
  949.      parentheses.  The various types of clauses specify
  950.      initializations, such as the binding of temporary variables,
  951.      actions to be taken in the loop, stepping actions, and final
  952.      cleanup.
  953.  
  954.      Common Lisp specifies a certain general order of clauses in a loop:
  955.  
  956.           (loop NAME-CLAUSE
  957.                 VAR-CLAUSES...
  958.                 ACTION-CLAUSES...)
  959.  
  960.      The NAME-CLAUSE optionally gives a name to the implicit block that
  961.      surrounds the loop.  By default, the implicit block is named
  962.      `nil'.  The VAR-CLAUSES specify what variables should be bound
  963.      during the loop, and how they should be modified or iterated
  964.      throughout the course of the loop.  The ACTION-CLAUSES are things
  965.      to be done during the loop, such as computing, collecting, and
  966.      returning values.
  967.  
  968.      The Emacs version of the `loop' macro is less restrictive about
  969.      the order of clauses, but things will behave most predictably if
  970.      you put the variable-binding clauses `with', `for', and `repeat'
  971.      before the action clauses.  As in Common Lisp, `initially' and
  972.      `finally' clauses can go anywhere.
  973.  
  974.      Loops generally return `nil' by default, but you can cause them to
  975.      return a value by using an accumulation clause like `collect', an
  976.      end-test clause like `always', or an explicit `return' clause to
  977.      jump out of the implicit block.  (Because the loop body is
  978.      enclosed in an implicit block, you can also use regular Lisp
  979.      `return' or `return-from' to break out of the loop.)
  980.  
  981.    The following sections give some examples of the Loop Macro in
  982. action, and describe the particular loop clauses in great detail.
  983. Consult the second edition of Steele's "Common Lisp, the Language", for
  984. additional discussion and examples of the `loop' macro.
  985.  
  986. 
  987. File: cl,  Node: Loop Examples,  Next: For Clauses,  Prev: Loop Basics,  Up: Loop Facility
  988.  
  989. Loop Examples
  990. -------------
  991.  
  992. Before listing the full set of clauses that are allowed, let's look at
  993. a few example loops just to get a feel for the `loop' language.
  994.  
  995.      (loop for buf in (buffer-list)
  996.            collect (buffer-file-name buf))
  997.  
  998. This loop iterates over all Emacs buffers, using the list returned by
  999. `buffer-list'.  For each buffer `buf', it calls `buffer-file-name' and
  1000. collects the results into a list, which is then returned from the
  1001. `loop' construct.  The result is a list of the file names of all the
  1002. buffers in Emacs' memory.  The words `for', `in', and `collect' are
  1003. reserved words in the `loop' language.
  1004.  
  1005.      (loop repeat 20 do (insert "Yowsa\n"))
  1006.  
  1007. This loop inserts the phrase "Yowsa" twenty times in the current buffer.
  1008.  
  1009.      (loop until (eobp) do (munch-line) (forward-line 1))
  1010.  
  1011. This loop calls `munch-line' on every line until the end of the buffer.
  1012. If point is already at the end of the buffer, the loop exits
  1013. immediately.
  1014.  
  1015.      (loop do (munch-line) until (eobp) do (forward-line 1))
  1016.  
  1017. This loop is similar to the above one, except that `munch-line' is
  1018. always called at least once.
  1019.  
  1020.      (loop for x from 1 to 100
  1021.            for y = (* x x)
  1022.            until (>= y 729)
  1023.            finally return (list x (= y 729)))
  1024.  
  1025. This more complicated loop searches for a number `x' whose square is
  1026. 729.  For safety's sake it only examines `x' values up to 100; dropping
  1027. the phrase `to 100' would cause the loop to count upwards with no
  1028. limit.  The second `for' clause defines `y' to be the square of `x'
  1029. within the loop; the expression after the `=' sign is reevaluated each
  1030. time through the loop.  The `until' clause gives a condition for
  1031. terminating the loop, and the `finally' clause says what to do when the
  1032. loop finishes.  (This particular example was written less concisely
  1033. than it could have been, just for the sake of illustration.)
  1034.  
  1035.    Note that even though this loop contains three clauses (two `for's
  1036. and an `until') that would have been enough to define loops all by
  1037. themselves, it still creates a single loop rather than some sort of
  1038. triple-nested loop.  You must explicitly nest your `loop' constructs if
  1039. you want nested loops.
  1040.  
  1041.